package dashboard.utils;

import java.io.*;

/**
 * 
 * @author xu guoneng
 *
 */
public class FileUtil {

	public static final String FILE_DIR = "D:/";
		
	/**
	 * Read content from file under /resource/sqlscripts/ folder
	 * @param scriptName
	 * @return
	 */
	public static String readSqlScript(String scriptName){
		InputStream is =  new FileUtil().getClass().getResourceAsStream("/sqlscripts/" + scriptName);
		java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
	    return s.hasNext() ? s.next() : "";
	}
	
	public static String readFile(String absoluteFileName){
		StringBuffer sb = new StringBuffer();
		
		BufferedReader br = null;
		 
		try {
 
			String sCurrentLine;
 
			br = new BufferedReader(new FileReader(absoluteFileName));
 
			while ((sCurrentLine = br.readLine()) != null) {
				sb.append(sCurrentLine).append("\n");
			}
		} 
		catch (IOException e) {
			e.printStackTrace();
		} 
		finally {
			try {
				if (br != null)br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		
		return sb.toString().trim();
	}
	
	/**
	 * Existing file with the same name will be overwritten
	 * @param simpleFileName
	 * @param content
	 */
	public static void writeFile(String simpleFileName, String content){
		try {
			File file = new File(FILE_DIR + simpleFileName);
			if (!file.exists()) {
				file.createNewFile();
			}
 
			FileWriter fw = new FileWriter(file.getAbsoluteFile(), false);
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(content);
			bw.close();
		} 
		catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	public static void deleteFile(String absoluteFileName){
		try{
			File f = new File(absoluteFileName);
			if(f.exists()){
				f.delete();
			}
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
	}
}
